#include "header.h"
#include "myepoll.hpp"
#include <iostream>
using namespace std;
#define BUFFER_SIZE 1024
int main()
{
    //char * sourceIP = "127.0.0.1";
    //char * sourcePort = "8080";

    const char * sourceIP = "8.148.75.183";
    const char * sourcePort = "9031";
    int clientfd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(clientfd, 0, "socket");

    struct sockaddr_in serveraddr;
    memset(&serveraddr, 0, sizeof(serveraddr));

    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port =htons(atoi(sourcePort));
    serveraddr. sin_addr.s_addr = inet_addr(sourceIP);

    int ret = connect(clientfd, (const struct sockaddr*)&serveraddr, sizeof(serveraddr));
    //ERROR_CHECK(ret, 0, "bind");

    MyEpoll epoll;
    epoll.add(clientfd, EPOLLIN, [clientfd](uint32_t events){
              char buffer[BUFFER_SIZE];
              memset(buffer, 0, sizeof(buffer));
              if (events & EPOLLIN){// 处理读事件
                    int ret = recv(clientfd, buffer, sizeof(buffer),0);
                    if(ret >0){
                        cout << "服务器发来：" << buffer << endl;
                    }
                    else if(ret == 0){
                        cout << "服务器断开" << endl;
                        close(clientfd);
                        exit(0);
                    }
                    else{
                        perror("recv");
                        close(clientfd);
                        exit(1);
                    }
              } 
              });
    epoll.add(STDIN_FILENO, EPOLLIN, [clientfd](uint32_t events){
              char buffer[BUFFER_SIZE];
              memset(buffer, 0, sizeof(buffer));
                  cout<<"检测到输入"<<buffer<<endl;
              if (events & EPOLLIN){
                  if (fgets(buffer, BUFFER_SIZE, stdin) != NULL) {
                  buffer[strcspn(buffer, "\n")] = '\0';// 移除末尾的换行符
                  send(clientfd, buffer, strlen(buffer), 0);
                  cout<<"已经发送"<<buffer<<endl;
                  }    
              }
              }); 
    while(1){
        epoll.wait(5000);
    }

    return 0;
};


